from django.shortcuts import render
from base_utils.views import APIView
from base_utils.response import Response
from base_utils.redis_pool import get_redis_client
from . import serializers
from base_utils.response_http_code import BadRequestStatus, SuccessStatus
from lua_script.seconds_kill import SeckillService

# Create your views here.


class SecondKillAPIView(APIView):
    def post(self, request, *args, **kwargs):
        ser = serializers.SecondKillSer(data=request.data)
        if ser.is_valid():
            ret = ser.save()
            code = ret.get("code")
            msg = ret.get("msg")
            return Response(code=code, msg=msg)
        else:
            msg = self.get_errors_str(ser.errors)
            return Response(code=BadRequestStatus.http_code, msg=msg)

    def put(self, request, *args, **kwargs):
        goods_id = request.data.get("goods_id")
        counts = request.data.get("counts")
        obj = SeckillService(redis_client=get_redis_client())
        is_true = obj.init_sec_kill_data(goods_id, counts)
        if is_true:
            code = SuccessStatus.http_code
            msg = "初始化成功"
        else:
            code = BadRequestStatus.http_code
            msg = "操作失败"
        return Response(code=code, msg=msg)
